import {TOKEN_KEY, USERINFO_KEY} from '@/utils/constants/index.js'
import {findMenu} from '@/components/aside/utils.js'
import useGlobalStore from '@/stores/global.js'

export default function beforeEach(router) {
  router.beforeEach((to, from, next) => {
    if (to.meta && to.meta.noToken) {
      setTitle(to)
      next()
    } else {
      // 判断token是否存在，若存在，则跳转，否则，不跳转
      const token = localStorage.getItem(TOKEN_KEY)
      // 判断当前当湖是否拥有当前页面的访问权限
      const auth = hasAuth(to)
      if (token && auth) {
        setTitle(to)
        next()
      } else {
        document.title = '登录'
        if (from?.name !== 'login') {
          router.push({ name: 'login' })
        }
      }
    }
  })
}

function setTitle(to) {
  const globalStore = useGlobalStore()
  const menu = findMenu(globalStore.menuList || [], to.name)
  if (menu) {
    document.title = menu.title
  } else {
    document.title = to.meta?.title || '管理系统'
  }
  // const menuItem = findMenu(menuList, index)
}

function hasAuth(to) {
  if (to.meta?.isTest) {
    return true
  }
  let userInfo: any = localStorage.getItem(USERINFO_KEY)
  userInfo = userInfo ? JSON.parse(userInfo) : null
  if (!userInfo) {
    return false
  }
  if (userInfo.roleInfoList.some(item => item.roleCode === 'admin')) {
    return true
  }
  return !!(userInfo.resourceInfoList || []).some(item => item.uniqueProp === to.name)

}
